package com.jin.webvideo.externalInterfaces.qqvideo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.externalInterfaces.PlatformSupport;
import com.jin.webvideo.externalInterfaces.entity.Filmography;
import com.jin.webvideo.externalInterfaces.entity.FilmographyInfo;
import com.jin.webvideo.util.sys.ClientUtil;
import com.jin.webvideo.util.base.StringUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QQBaseInfoHandle {
    //id=cfrygt95a6j2vor & t=
    private static final String URL = //"https://pbaccess.video.qq.com/trpc.universal_backend_service.page_server_rpc.PageServer/GetPageData?video_appid=3000010&vplatform=2";
                                      "https://pbaccess.video.qq.com/trpc.universal_backend_service.page_server_rpc.PageServer/GetPageData?video_appid=3000010&vplatform=2&vversion_name=8.2.96";
    private static final String VIDEOINFO_FORM_DATA = "{\"page_params\":{\"req_from\":\"web_vsite\",\"page_id\":\"vsite_episode_list\",\"page_type\":\"detail_operation\",\"id_type\":\"1\",\"page_size\":\"\",\"cid\":\"%s\",\"vid\":\"\",\"lid\":\"\",\"page_num\":\"\",\"page_context\":\"chapter_name=&cid=%s&detail_page_type=1&episode_begin=%d&episode_end=%d&episode_step=%d&filter_rule_id=&id_type=1&is_nocopyright=false&lid=&list_page_context=&need_tab=1&order=&page_num=%d&page_size=%d&req_from=web_vsite&req_from_second_type=&req_type=0&siteName=&tab_type=1&title_style=&ui_type=null&un_strategy_id=13dc6f30819942eb805250fb671fb082&watch_together_pay_status=0&year=\",\"detail_page_type\":\"1\"},\"has_cache\":1}";
    private static final String BASEINFO_FORM_DATA = "{\"page_params\":{\"req_from\":\"web\",\"cid\":\"%s\",\"vid\":\"\",\"lid\":\"%s\",\"page_type\":\"detail_operation\",\"page_id\":\"detail_page_introduction\"},\"has_cache\":1}";
        private static final String COL_ID_URL = "https://union.video.qq.com/fcgi-bin/data?appid=20001238&appkey=6c03bbe9658448a4&idlist=%s&otype=json&tid=1803&_=%d&callback=a";

    private static final String VIDEOINFO_URL = "http://s.video.qq.com/get_playsource?id=%s&type=4&data_type=3&range=%s-%s&plname=qq&otype=json&callback=a&_t=%d";

    private static Map<String, String> header;
    static {
        header = new HashMap<>();
        header.put("cookie", "vversion_name=8.2.95;");
        header.put("referer", "https://v.qq.com/");
        header.put("content-type", "application/json;charset=UTF-8");
        header.put("accept", "application/json, text/plain, */*");
    }
    public List<FilmographyInfo> videoInfos(String docid, String tvid, int pageNo, int pageSize) throws IOException {
        pageSize = 30;
        String formData = String.format(VIDEOINFO_FORM_DATA, docid, docid, pageNo*pageSize + 1, (pageNo+1)*pageSize, pageSize, pageNo, pageSize);
        Result result = request(URL, formData);
        if (null == result){
            throw new IOException(String.format("no such result with docid=%s and tvid=%s", docid, tvid));
        }
        JSONArray array = result.getItemData();
        List<FilmographyInfo> infos  = toVideoInfo(array);
        if (result.hasNext(pageNo)){
            // 添加pageNo防止未考虑到的死循环
            if (pageNo > 20){
                throw new IOException("请确认是否出现死循环 docid=" +docid);
            }
            List<FilmographyInfo> nextPage = videoInfos(docid, tvid, ++pageNo, pageSize);
            infos.addAll(nextPage);
        }
        return infos;
    }
    public String getColId(String docid) throws IOException {
        String url = String.format(COL_ID_URL, docid, System.currentTimeMillis());
        String data = ClientUtil.httpGet(url);
        data = StringUtil.substringTrim(data, 2);
        data = StringUtil.substringTrim(data, -1);
        JSONObject rst = JSONObject.parseObject(data);
        if (0 != rst.getInteger("errorno")){
            return "0";
        }
        JSONArray results = rst.getJSONArray("results");
        if (results.size()< 1){
            return "0";
        }
        JSONObject result = results.getJSONObject(0);
        JSONObject fields = result.getJSONObject("fields");
        String columnId = fields.getString("column_id");
        if (null == columnId){
            return "";
        }
        return columnId;
    }
    public Result request(String url, String formData) throws IOException {
        String data = ClientUtil.httpPost(url, header, formData);
        JSONObject result = JSONObject.parseObject(data);
        if (0 == result.getInteger("ret") && result.containsKey("data")){
            return JSONObject.parseObject(data, Result.class);
        }
        return null;
    }
    public Filmography baseInfo(String docid, String tvid) throws IOException {
        Filmography filmography = new Filmography();
        String formData = String.format(BASEINFO_FORM_DATA, docid, getColId(docid));
        Result result = request(URL, formData);
        if (null == result){
            throw new IOException(String.format("no such result with docid=%s and tvid=%s", docid, tvid));
        }
        JSONArray array = result.getItemData();
        JSONObject obj = array.getJSONObject(0).getJSONObject("item_params");
        filmography.setImg(obj.getString("new_pic_vt"));
        filmography.setYear(obj.getString("year"));
        filmography.setPlatform(PlatformSupport.PLATFORM_QQ);
        filmography.setPlatformName(PlatformSupport.PLATFORM_NAME_QQ);
        filmography.setId(obj.getString("report.cid"));
        filmography.setName(obj.getString("title"));
        String desc = StringUtil.getDefault(obj.getString("cover_description"), obj.getString("video_description"));
        filmography.setDesc(desc);
        JSONObject tag = JSONObject.parseObject(obj.getString("imgtag_ver"));
        String videoMate = tag.getJSONObject("tag_3").getString("text");
        filmography.setVideoMate(StringUtil.getDefault(videoMate, obj.getString("hotval")));
        filmography.setTag(obj.getString("main_genres"));
        return filmography;
    }
    public List<FilmographyInfo> videoInfos(String docid, String start, String end) throws IOException {
        if (start.equals("0")){
            start = "1";
        }
        List<FilmographyInfo> infos = new ArrayList<>();
        String url = String.format(VIDEOINFO_URL, docid, start, end, System.currentTimeMillis());
        String json = ClientUtil.httpGet(url);
        json = StringUtil.substringTrim(json, 2);
        json = StringUtil.substringTrim(json, -1);
        JSONObject result = JSONObject.parseObject(json);
        if (null != result && 0 == result.getInteger("error") && null != result.getJSONObject("PlaylistItem") ){
            JSONObject object = result.getJSONObject("PlaylistItem");
            JSONArray array = object.getJSONArray("videoPlayList");
            infos = toVideoInfo2(array);
        }
        return infos;
    }

    public List<FilmographyInfo> toVideoInfo2(JSONArray array){
        List<FilmographyInfo> infos = new ArrayList<>();
        if (null == array){
            return infos;
        }
        int size = array.size();
        for (int i = array.size() - 1; i > -1; i --){
            JSONObject obj = array.getJSONObject(i);
            if (!"1".equals(obj.getString("type"))){
                continue;
            }
            FilmographyInfo filmographyInfo = new FilmographyInfo();
            int number = size - i;
            if (StringUtil.isNumber(obj.getString("episode_number"))){
                number = obj.getInteger("episode_number");
            }
            filmographyInfo.setNumber(number);
            filmographyInfo.setId( obj.getString("id") );
            filmographyInfo.setTitle( obj.getString("title") );
            filmographyInfo.setUrl(obj.getString("playUrl"));
            filmographyInfo.setPlatform( PlatformSupport.PLATFORM_QQ );
            filmographyInfo.setDisplayMode(FilmographyInfo.DISPLAY_MODE_INDEX_BLOCK);
            infos.add(filmographyInfo);
        }
        return infos;
    }



    public List<FilmographyInfo> toVideoInfo(JSONArray array){
        List<FilmographyInfo> infos = new ArrayList<>();
        if (null == array){
            return infos;
        }
        int number = 0;
        for (int i = 0; i < array.size(); i++){
            JSONObject obj = array.getJSONObject(i);
            obj = obj.getJSONObject("item_params");
            if ( obj.containsKey("page_type") ) {
                continue;
            }
            if (obj.getString("imgtag_all").contains("\"预")){
                continue;
            }
            FilmographyInfo filmographyInfo = new FilmographyInfo();
            number ++;

            Integer mode = FilmographyInfo.DISPLAY_MODE_TITLE_BLOCK;
            if (StringUtil.isNumber(obj.getString("title"))){
                number = obj.getInteger("title");
                mode = FilmographyInfo.DISPLAY_MODE_INDEX_BLOCK;
            }

            filmographyInfo.setDisplayMode(mode);
            filmographyInfo.setNumber(number);
            filmographyInfo.setId( obj.getString("vid") );
            String title = StringUtil.getDefault(obj.getString("title"), obj.getString("play_title"));
            filmographyInfo.setTitle(title);
            filmographyInfo.setUrl(getUrl(obj.getString("cid"), filmographyInfo.getId()));
            filmographyInfo.setPlatform( PlatformSupport.PLATFORM_QQ );
            infos.add(filmographyInfo);
        }
        return infos;
    }
    private String getUrl(String docid, String tvid){
        if (StringUtil.isEmpty(tvid)){
            return String.format("https://v.qq.com/x/cover/%s.html", docid);
        }
        return String.format("https://v.qq.com/x/cover/%s/%s.html", docid, tvid);
    }
}
